import React, { useState, useRef, useEffect } from 'react';
import { FiMenu, FiSearch, FiDownload, FiClock } from 'react-icons/fi';

// 添加样式常量
const tickerStyles = {
  ticker: {
    width: '300px',
    height: '60px',
    overflow: 'hidden',
    position: 'relative',
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    borderRadius: '4px',
    padding: '0 12px',
    display: 'flex',
    alignItems: 'center',
    border: '1px solid rgba(0, 229, 255, 0.3)',
    boxShadow: '0 0 8px rgba(0, 229, 255, 0.3)'
  },
  content: {
    position: 'absolute',
    width: '100%',
    display: 'flex',
    flexDirection: 'column'
  },
  message: {
    color: '#00e5ff',
    fontSize: '14px',
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    padding: '8px 0'
  },
  prefix: {
    color: '#ffffff',
    fontWeight: 'bold',
    marginRight: '6px'
  },
  placeholder: {
    color: 'rgba(255, 255, 255, 0.5)',
    fontStyle: 'italic',
    fontSize: '14px'
  }
};

const Header = ({ onMenuClick, onNavClick, activePage }) => {
  const [menuOpen, setMenuOpen] = useState(false);
  const [currentTime, setCurrentTime] = useState(new Date());
  const [colonVisible, setColonVisible] = useState(true);
  const [iconOpacity, setIconOpacity] = useState(0.8);
  const [messages, setMessages] = useState([]);
  const [currentMessageIndex, setCurrentMessageIndex] = useState(0);
  const menuRef = useRef(null);
  const tickerRef = useRef(null);

  // WebSocket连接
  useEffect(() => {
    let socket;
    let reconnectAttempts = 0;
    const maxReconnectAttempts = 5;
    const reconnectDelay = 3000; // 3秒重试间隔

    const connectWebSocket = () => {
      socket = new WebSocket('ws://127.0.0.1:8001/ws/analysis/');
      
      socket.onopen = () => {
        console.log('WebSocket连接成功');
        reconnectAttempts = 0; // 重置重连计数器
      };

      socket.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          if (data.type === 'task_completed') {
            setMessages(prev => [...prev, {
              id: Date.now(),
              content: data.message
            }]);
          }
        } catch (error) {
          console.error('处理WebSocket消息出错:', error);
        }
      };

      socket.onerror = (error) => {
        console.error('WebSocket错误:', error);
      };

      socket.onclose = (event) => {
        if (event.wasClean) {
          console.log(`WebSocket连接关闭，状态码: ${event.code}, 原因: ${event.reason}`);
        } else {
          console.error('WebSocket连接异常断开');
          if (reconnectAttempts < maxReconnectAttempts) {
            reconnectAttempts++;
            console.log(`尝试重新连接 (${reconnectAttempts}/${maxReconnectAttempts})...`);
            setTimeout(connectWebSocket, reconnectDelay);
          }
        }
      };
    };

    connectWebSocket();

    return () => {
      if (socket) {
        socket.close();
      }
    };
  }, []);

  // 消息滚动效果
  useEffect(() => {
    const interval = setInterval(() => {
      if (messages.length > 0) {
        setCurrentMessageIndex(prev => 
          (prev + 1) % messages.length
        );
      }
    }, 5000); // 每5秒切换一次消息

    return () => clearInterval(interval);
  }, [messages]);
  
  // 更新时间的定时器
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);
    
    const blinkTimer = setInterval(() => {
      setColonVisible(prev => !prev);
    }, 500);
    
    const pulseTimer = setInterval(() => {
      setIconOpacity(prev => prev === 0.8 ? 1 : 0.8);
    }, 2000);
    
    return () => {
      clearInterval(timer);
      clearInterval(blinkTimer);
      clearInterval(pulseTimer);
    };
  }, []);
  
  // 格式化日期时间
  const formatDateTime = () => {
    const year = currentTime.getFullYear();
    const month = String(currentTime.getMonth() + 1).padStart(2, '0');
    const day = String(currentTime.getDate()).padStart(2, '0');
    const hours = String(currentTime.getHours()).padStart(2, '0');
    const minutes = String(currentTime.getMinutes()).padStart(2, '0');
    const seconds = String(currentTime.getSeconds()).padStart(2, '0');
    
    return {
      date: `${year}-${month}-${day}`,
      time: { hours, minutes, seconds }
    };
  };
  
  const toggleMenu = () => {
    setMenuOpen(!menuOpen);
  };
  
  const handleMenuItemClick = (action) => {
    setMenuOpen(false);
    if (action === 'download') {
      // 处理下载市场数据的逻辑
      console.log('下载市场数据');
      // 这里可以导航到下载页面或打开模态框
      if (onMenuClick) {
        onMenuClick('download');
      }
    }
  };
  
  // 点击外部关闭菜单
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (menuRef.current && !menuRef.current.contains(event.target)) {
        setMenuOpen(false);
      }
    };
    
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);
  const navItems = [
    { id: 'home', label: '首页', path: '/' },
    { id: 'market-review', label: '市场复盘', path: '/market-review' },
    { id: 'real-time', label: '实时交易', path: '/real-time' },
    { id: 'strategy', label: '操盘策略', path: '/strategy' },
    { id: 'stock-finder', label: '个股分类', path: '/stock' },
    { id: 'training', label: '模型训练', path: '/training' },
  ];

  return (
    <header className="app-header">
      <div className="header-left">
        <div className="menu-container" ref={menuRef}>
          <button className="menu-btn" onClick={toggleMenu}>
            <FiMenu size={20} />
          </button>
          {menuOpen && (
            <div className="menu-dropdown">
              <div className="menu-item" onClick={() => handleMenuItemClick('download')}>
                <FiDownload className="menu-item-icon" />
                <span>下载市场数据</span>
              </div>
              {/* 这里可以添加更多菜单项 */}
            </div>
          )}
        </div>
        <div className="logo">
          <span className="logo-text">QuantVision</span>
          <span className="logo-badge">PRO</span>
        </div>
        <div className="datetime-display" style={{ 
          marginLeft: '15px', 
          fontFamily: 'monospace', 
          fontSize: '16px', 
          color: '#00e5ff', 
          background: 'rgba(0, 0, 0, 0.7)', 
          padding: '4px 12px', 
          borderRadius: '4px', 
          boxShadow: '0 0 8px rgba(0, 229, 255, 0.3), inset 0 0 10px rgba(0, 229, 255, 0.1)', 
          display: 'flex', 
          alignItems: 'center',
          border: '1px solid rgba(0, 229, 255, 0.3)',
          position: 'relative',
          letterSpacing: '0.5px',
          gap: '8px'
        }}>
          <FiClock size={16} style={{
            color: '#00e5ff',
            opacity: iconOpacity,
            transition: 'opacity 0.5s ease-in-out',
            marginRight: '2px',
            filter: 'drop-shadow(0 0 2px rgba(0, 229, 255, 0.5))'
          }} />
          <div style={{
            position: 'absolute',
            top: '0',
            left: '0',
            right: '0',
            height: '1px',
            background: 'linear-gradient(90deg, transparent, rgba(0, 229, 255, 0.5), transparent)',
            opacity: '0.5'
          }}/>
          <span style={{
            padding: '0 8px 0 0',
            borderRight: '1px solid rgba(0, 229, 255, 0.3)'
          }}>
            {formatDateTime().date}
          </span>
          <span style={{
            padding: '0 0 0 8px',
            display: 'flex',
            alignItems: 'center'
          }}>
            {formatDateTime().time.hours}
            <span style={{
              opacity: colonVisible ? 1 : 0.3,
              padding: '0 2px',
              transition: 'opacity 0.1s'
            }}>:</span>
            {formatDateTime().time.minutes}
            <span style={{
              opacity: colonVisible ? 1 : 0.3,
              padding: '0 2px',
              transition: 'opacity 0.1s'
            }}>:</span>
            {formatDateTime().time.seconds}
          </span>
          <div style={{
            position: 'absolute',
            bottom: '0',
            left: '0',
            right: '0',
            height: '1px',
            background: 'linear-gradient(90deg, transparent, rgba(0, 229, 255, 0.5), transparent)',
            opacity: '0.5'
          }}/>
        </div>
      </div>
      
      <nav className="main-nav">
        {navItems.map(item => (
          <button
            key={item.id}
            className={`nav-item ${activePage === item.id ? 'active' : ''}`}
            onClick={() => {onNavClick(item.id);}}
          >
            {item.label}
            {activePage === item.id && <div className="nav-indicator"></div>}
          </button>
        ))}
      </nav>
      
      <div className="header-right">
        <div className="search-box">
          <FiSearch className="search-icon" />
          <input type="text" placeholder="搜索市场、股票或策略..." />
        </div>
        <div className="message-ticker" ref={tickerRef} style={tickerStyles.ticker}>
          {messages.length > 0 && (
            <div 
              className="ticker-content" 
              style={{
                ...tickerStyles.content,
                transform: `translateY(-${currentMessageIndex * 100}%)`,
                transition: 'transform 0.5s ease-in-out'
              }}
            >
              {messages.map((msg) => (
                <div key={msg.id} style={tickerStyles.message}>
                  <span style={tickerStyles.prefix}>分析结果:</span> {msg.content}
                </div>
              ))}
            </div>
          )}
          {messages.length === 0 && (
            <div style={tickerStyles.placeholder}>
              等待分析数据...
            </div>
          )}
        </div>
      </div>
    </header>
  );
};

export default Header;
